package mysql

import (
	"fmt"
	"go.uber.org/zap"
	"goconfcenter/models"
	"goconfcenter/service/dto/bus"
)

type OperationLogDao struct {
}

func OperationLogDaoInstance() *OperationLogDao {
	return &OperationLogDao{}
}
func (c *OperationLogDao) Insert(operationLog *models.OperationLog) *models.OperationLog {
	result := db.Create(&operationLog)
	if result.Error == nil {
		return operationLog
	} else {
		zap.L().Error("插入出错", zap.Error(result.Error))
		return nil
	}
}
func (c *OperationLogDao) PageByQuery(params *bus.OperationLogQuery) ([]*models.OperationLogPoJo, int64) {
	var total int64
	whereSql := " 1= 1 "
	data := make([]*models.OperationLogPoJo, 0)

	if params.OperTag != "" {
		whereSql = whereSql + fmt.Sprintf(" and sys_operation_log.oper_tag like %q ", ("%"+params.OperTag+"%"))
	}
	if params.OperatorId > 0 {
		whereSql = whereSql + fmt.Sprintf(" and sys_operation_log.operator_id = %d ", params.OperatorId)
	}
	if params.OperatorName != "" {
		whereSql = whereSql + fmt.Sprintf(" and T1.real_name like %q ", ("%"+params.OperatorName+"%"))
	}
	if params.RequestUriLike != "" {
		whereSql = whereSql + fmt.Sprintf(" and sys_operation_log.request_uri like %q ", ("%"+params.RequestUriLike+"%"))
	}
	//默认排序
	sortOrder := "sys_operation_log.ID"
	switch params.SortOrder {
	case "ID":
		sortOrder = "id"
	}
	if params.SortOrder == "desc" {
		sortOrder = "  " + sortOrder
	}
	// 分页查询
	offset := (params.PageNum - 1) * params.PageSize
	query := db.Table("sys_operation_log").Select(" sys_operation_log.*,T1.real_name As operatorName ")
	query = query.Joins(" Inner Join rms_backend_user As T1 on T1.id = sys_operation_log.operator_id ")
	err := query.Where(whereSql).Count(&total).Limit(params.PageSize).Offset(offset).Order(sortOrder).Find(&data).Error
	if err != nil {
		fmt.Println(err)
	}
	return data, total
}
